﻿using Seggu.Daos.Interfaces;
using Seggu.Dtos;
using Seggu.Data;
using Seggu.Services.DtoMappers;
using Seggu.Services.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;

namespace Seggu.Services
{
    public sealed class VehicleTypeService : IVehicleTypeService
    {
        private IVehicleTypeDao VehicleTypeDao;

        public VehicleTypeService(IVehicleTypeDao VehicleTypeDao)
        {
            this.VehicleTypeDao = VehicleTypeDao;
        }
        public IEnumerable<VehicleTypeDto> GetAll()
        {
            var vehicletype = this.VehicleTypeDao.GetAll();
            return vehicletype.OrderBy(x => x.Name).Select(vt => VehicleTypeDtoMapper.GetDto(vt));
        }
        public void Save(VehicleTypeDto vType)
        {
            var vehicleType = VehicleTypeDtoMapper.GetObject(vType);
            AttachContextBodyworks(vehicleType);
            AttachContextUses(vehicleType);
            this.VehicleTypeDao.Save(vehicleType);
        }
            private void AttachContextBodyworks(VehicleType vehicleType)
            {
                var bodyworks = new List<Bodywork>();
                foreach (var item in vehicleType.Bodyworks)
                    bodyworks.Add(VehicleTypeDao.GetContainer().Bodyworks.Single(x => x.Id == item.Id));
                vehicleType.Bodyworks = bodyworks;
            }
            private void AttachContextUses(VehicleType vehicleType)
            {
                var uses = new List<Use>();
                foreach (var item in vehicleType.Uses)
                    uses.Add(VehicleTypeDao.GetContainer().Uses.Single(x => x.Id == item.Id));
                vehicleType.Uses = uses;
            }
    }
}
